package com.suke.czx.modules.wx.controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class BaseController {
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	public HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	
	public ServletContext getServletContext() {
		return getSession().getServletContext();
	}
	
	/**
	 * 获取真实路径
	 */
	protected String getRealPath(String path) {
		return getServletContext().getRealPath(path);
	}
	
	/**
	 * 获取请求参数
	 */
	protected String param(String name) {
		return getRequest().getParameter(name);
	}
	
	/**
	 * 获取请求参数数组
	 */
	protected String[] params(String name) {
		return getRequest().getParameterValues(name);
	}
	
	/**
	 * 获取int类型请求参数
	 */
	protected int intParam(String name) {
		return Integer.parseInt(param(name));
	}

	/**
	 * 获取int类型请求参数,当出错时,返回defaultValue
	 */
	protected int intParam(String name,int defaultValue) {
		try {
			return Integer.parseInt(param(name));
		} catch(Exception e) {
			return defaultValue;
		}
	}
	
	/**
	 * 设置attribute到request中
	 */
	protected void attr(String name,Object value) {
		getRequest().setAttribute(name, value);
	}
	
	/**
	 * 从request中获取attribute
	 */
	protected Object attr(String name) {
		return getRequest().getAttribute(name);
	}
	
	/**
	 * 设置attribute到session中
	 */
	protected void sessAttr(String name,Object value) {
		getSession().setAttribute(name, value);
	}
	
	/**
	 * 从session中获取attribute
	 */
	protected Object sessAttr(String name) {
		return getSession().getAttribute(name);
	}
	
	/**
	 * 设置attribute到application中
	 */
	protected void appAttr(String name,Object value) {
		getServletContext().setAttribute(name, value);
	}
	
	/**
	 * 从application中获取attribute
	 */
	protected Object appAttr(String name) {
		return getServletContext().getAttribute(name);
	}
}
